'''
爬取91看剧的电视剧
'''

import requests
import re
'''
下载m3u8文件
'''
# obj = re.compile(r"url: '(?P<v_url>.*?)',", re.S) #提取m3u8地址
# heards = {
#     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"
# }
# url = "https://91kanju2.com/vod-play/54812-1-1.html"
#
# resp = requests.get(url=url, headers=heards)
# m3u8url = obj.search(resp.text).group("v_url")
# print(m3u8url)
# resp2 = requests.get(url=m3u8url, headers=heards)
# with open("./文件/哲人王后.m3u8", mode="wb") as f:
#     f.write(resp2.content)
#
# resp2.close()
# print("over")
'''
解析
'''
# n = 1
# with open("./文件/哲人王后.m3u8", mode="r", encoding="utf-8") as f:
#     for line in f:
#         line = line.strip()
#         if line.startswith('#'):
#             continue
#         resp3 = requests.get(line)
#         f = open(f'./文件/{n}.ts', mode='wb')
#         f.write(resp3.content)
#         f.close()
#         resp3.close()
#         n += 1
#         print("完成了{}".format(n))
heards = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"

}
from lxml import etree
import aiohttp
import asyncio
import aiofiles

def download_m3u8_filr(url, name):
    resp = requests.get(url=url)
    with open("./文件/"+name, mode="wb") as f:
        f.write(resp.content)

def get_first__m3u8url(url):
    resp = requests.get(url=url, headers=heards)
    obj = re.compile(r'var main = "(?P<m3u8_url>.*?)";', re.S)
    return url.split("/share")[0] + obj.search(resp.text).group("m3u8_url")

def get_v_urls(url):
    # obj1 = re.compile("", re.S)
    resp = requests.get(url=url, headers=heards)
    resp.encoding = "utf-8"
    t = resp.text
    html = etree.HTML(t)
    li = html.xpath("/html/body/div[5]/div[3]/*[2]/*[1]/ul/li/input/@value")
    return li

async def download_ts(url, name, session):
    async with session.get(url) as resp:
        async with aiofiles.open("./文件/" + name, mode="wb") as f:
            await f.write(await resp.content.read())
    print(f'{name}下载完毕!')

async def aio_download():
    tasks = []
    i = 100000
    async with aiohttp.ClientSession() as session:
        async with aiofiles.open("./文件/第二个m3u8.txt", mode="r", encoding="utf-8") as f:
            async for line in f:
                if line.startswith("#"):
                    continue
                line = line.strip()
                task = asyncio.create_task(download_ts(line, str(i) + ".ts", session))
                i += 1
                tasks.append(task)

            await asyncio.wait(tasks) #等待任务结束
def get_key(url):
    resp = requests.get(url=url, headers=heards)
    print(resp.text)

from Cryptodome.Cipher import AES

async def dec_ts(name, key):
    # aes = AES.new(key=key.encode("utf-8"), IV="0102030405060708".encode("utf-8"), mode=AES.MODE_CBC)
    aes = AES.new(key=key.encode("utf-8"), IV="0000000000000000".encode("utf-8"), mode=AES.MODE_CBC)
    async with aiofiles.open(f"./文件/{name}", mode="rb") as f1, \
            aiofiles.open(f"./文件/new_{name}", mode="wb") as f2:
        bs = await f1.read()
        await f2.write(aes.decrypt(bs))
    print(f"{name}处理完毕!")



async def aio_dec(key):
    tasks = []
    i = 100000
    async with aiofiles.open("./文件/第二个m3u8.txt", mode="r", encoding="utf-8") as f:
        async for line in f:
            if line.startswith("#"):
                continue
            line = line.strip()
            task = asyncio.create_task(dec_ts(str(i) + ".ts", key))
            i += 1
            tasks.append(task)
        await asyncio.wait(tasks)



def main(url):
    v_urls = get_v_urls(url)
    for u in v_urls[:1]:
        # first_m3u8 = get_first__m3u8url(u)
        # https://pps.sd-play.com/20220408/QbLRgXiL/index.m3u8
        # /20220408/QbLRgXiL/1200kb/hls/index.m3u8
        # download_m3u8_filr(first_m3u8, "第一个m3u8.txt")
        # second_m3u8 = ""
        # with open("./文件/第一个m3u8.txt", mode="r", encoding="utf-8") as f:
        #     for line in f:
        #         if line.startswith("#"):
        #             continue
        #         second_m3u8 = first_m3u8.split(".com")[0] + ".com" + line.strip()
        #         download_m3u8_filr(second_m3u8, "第二个m3u8.txt")
                # 下载
        # asyncio.run(aio_download())

        #密钥
        # key_url = "https://pps.shanshanku.com/20220408/QbLRgXiL/1200kb/hls/key.key"
        # key = get_key(key_url)

        #解密
        asyncio.run(aio_dec("91cb2a48c9b9dee9"))



if __name__ == '__main__':
    url = "http://shandianzy.com/index.php/vod/detail/id/43076.html"
    main(url)

